﻿using Castle.DynamicProxy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Extensions.Interceptor.Cache.Keys;

public class KeyContext
{
    private readonly IEnumerable<BaseStrategy> _strategies;

    public KeyContext(IEnumerable<BaseStrategy> strategies)
    {
        _strategies = strategies;
    }
    /// <summary>
    /// 创建cachekey
    /// </summary>
    /// <param name="keyExpression"></param>
    /// <param name="value"></param>
    /// <returns></returns>
    public string CreateKey(string keyExpression, IInvocation invocation)
    {
        var keys = keyExpression.Split("#", StringSplitOptions.RemoveEmptyEntries);
        // 表达式用#隔开然后可以配置多个 会按照顺序 然后把所有的表达式拼接
        var list = new List<string>();
        foreach (var key in keys)
        {
            var strategy = _strategies.FirstOrDefault(p =>p.KeyStrategyEnum.ToString().Equals(key, StringComparison.OrdinalIgnoreCase));
            // 如果没有定义 那么就是直接当做key  拼接进key
            if (strategy!=null)
            {
                list.Add(strategy.GetKey(invocation));
            }
            else
            {
                list.Add(key);
            }
        }
        return string.Join(":", list);
    }
}